/*
 * Copyright (c) 2014 Strong Group - 版权所有
 * 
 * This software is the confidential and proprietary information of
 * Strong Group. You shall not disclose such confidential information 
 * and shall use it only in accordance with the terms of the license 
 * agreement you entered into with www.cnstrong.cn.
 */
package com.zuorenke.serialize;

import com.zuorenke.serialize.support.hessian.Hessian2Serialization;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

@Slf4j
public class DefaultSerializableAdapter implements SerializableAdapter {

	@Override
	public byte[] serialize(Object object) {
		if(null == object){
			return new byte[0];
		}
		
		byte[] result = null;
		ByteArrayOutputStream bos = null;
		ObjectOutput oo = null;
		try {
			bos = new ByteArrayOutputStream();
			oo = new Hessian2Serialization().serialize(bos);
			oo.writeObject(object);
			oo.flushBuffer();
			result = bos.toByteArray();
		} catch (IOException e) {
			log.error("IOException {}", e);
		} finally {
			try {
				if(null != bos){
					bos.close();
				}
			} catch (IOException e) {
				log.error("IOException {}", e);
			}
		}
		return result;
	}

	@Override
	public Object deserialize(byte[] value) {
		if(value == null){
			return null;
		}
		
		Object result = null;
		ByteArrayInputStream bis = null;
		ObjectInput oi = null;
		try {
			bis = new ByteArrayInputStream(value);
			oi = new Hessian2Serialization().deserialize( bis);
			result = oi.readObject();
		} catch (IOException | ClassNotFoundException e) {
			log.error("Exception {}", e);
		} finally {
			try {
				if(null!=bis){
					bis.close();
				}
			} catch (IOException e) {
				log.error("IOException {}", e);
			}
		}
		return result;
	}
}
